package cn.fengsweb.tokyotyrant
{
	import cn.fengsweb.socket.SocketProxy;
	import cn.fengsweb.socket.SocketProxyEvent;
	import cn.fengsweb.socket.SocketProxyStatus;
	
	import flash.utils.ByteArray;
	
	internal class TokyoTyrantConnection
	{
		private var _sp:SocketProxy;
		
		private var _sendBytes:ByteArray;
		private var _feedback:Function;
		private var _autoClose:Boolean;
		
		public function get connected():Boolean
		{
			return _sp.connected;
		}
		
		public function TokyoTyrantConnection(host:String, port:uint, autoClose:Boolean=true)
		{
			_sp		= new SocketProxy();
			_sp.connect(host, port);
			
			_autoClose	= autoClose;
			
			addListener();
		}
		
		//-----------------------add and remove listener start-----------------------
		private function addListener():void
		{
			_sp.addEventListener(SocketProxyEvent.RECV,		onRecv);
			_sp.addEventListener(SocketProxyEvent.STATUS,	onStatus);
		}
		private function removeListener():void
		{
			_sp.removeEventListener(SocketProxyEvent.RECV,		onRecv);
			_sp.removeEventListener(SocketProxyEvent.STATUS,	onStatus);
		}
		//-----------------------add and remove listener end-----------------------
		
		//-----------------------send request and get responder start-----------------------
		public function connect(sendBytes:ByteArray, feedback:Function=null):void
		{
			if(feedback != null){
				_feedback	= feedback;
			}
			
			if(_sp.connected){
				_sp.send(sendBytes);
			}else{
				_sendBytes	= sendBytes;
			}
		}
		private function onRecv(e:SocketProxyEvent):void
		{
			if(_feedback != null){
				_feedback(0, e.recvBytes);
				
				if(_autoClose){
					close();
				}
			}
		}
		private function onStatus(e:SocketProxyEvent):void
		{
			switch(e.statusType){
				case SocketProxyStatus.CONNECT:
					if(_sendBytes != null){
						_sp.send(_sendBytes);
					}
					break;
				default:
					if(_feedback != null){
						_feedback(e.statusType);
						close();
					}
			}
		}
		//-----------------------send request and get responder end-----------------------
		
		//-----------------------close start-----------------------
		public function close():void
		{
			_sp.disconnect();
			removeListener();
		}
		//-----------------------close start-----------------------
	}
}